package com.hdjd.controller;

import com.hdjd.entities.Account;
import com.hdjd.entities.Admin;
import com.hdjd.entities.School;
import com.hdjd.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 黄徵岚
 * @create 2021/1/26 14:19
 */
@RequestMapping("/login")
@Controller
public class LoginController {

    @Autowired
    private AccountService accountService;

    @ResponseBody
    @RequestMapping(value = "/loginShop",method = RequestMethod.POST)
    public Map<String,Object>
    loginShop(String stuNo, @RequestParam(value = "accName",required = false) String accName, String accPwd, HttpSession session){
        Object accountObject = null;
        Map<String,Object> map = new HashMap<>();
        try{
            accountObject = accountService.selectAccountByStuNoOrAccNameAndAccPwd(stuNo, accName, accPwd);
        }catch (Exception e){
            e.printStackTrace();
            map.put("code", 1002);
            map.put("msg", "登录失败");
            return map;
        }
        if (accountObject != null){
            if (accountObject.getClass() == Account.class){
                Account account = (Account)accountObject;
                session.setAttribute("account",account);
                map.put("code", 1001);
                map.put("msg", "登录成功");
                map.put("role","account");
            }else if (accountObject.getClass() == Admin.class){
                Admin admin = (Admin)accountObject;
                session.setAttribute("admin",admin);
                map.put("code", 1001);
                map.put("msg", "登录成功");
                map.put("role","admin");
            }else if (accountObject.getClass() == School.class){
                School school = (School) accountObject;
                session.setAttribute("school",school);
                map.put("code", 1001);
                map.put("msg", "登录成功");
                map.put("role","school");
            }else {
                map.put("code", 1002);
                map.put("msg", "院校已停用");
                return map;
            }
            return map;
        }else {
            map.put("code", 1002);
            map.put("msg", "你输入的帐号或密码不正确，请重新输入。");
            return map;
        }

    }
    //退出登录
    @RequestMapping(value = "/logoutShop")
    public String logoutShop(HttpSession session){
            //使session强制失效
            session.invalidate();

            return "redirect:/login.jsp";
        }


}
